package com.kischang.blog.web.action;

import com.kischang.blog.model.Reply;
import com.kischang.blog.model.Review;
import com.kischang.blog.model.User;
import com.kischang.blog.service.ReplyService;
import com.kischang.blog.service.ReviewService;
import com.kischang.blog.service.TopicService;
import com.kischang.blog.utils.Utils;
import com.kischang.blog.web.actionuser.LoginAction;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class ReplyAction extends ActionSupport {

	private static final long serialVersionUID = -6688055124669165386L;
	@Autowired
	private ReplyService replyService;
	@Autowired
	private ReviewService reviewService;
	@Autowired
	private TopicService topicService;
	private String content;
	private int pid;
	private int rid;
	private String msg;
	private int stat;
	
	@Override
	public String execute() throws Exception {
		User author = (User) ActionContext.getContext().getSession().get(LoginAction.SESSION_USER);
		if(author == null ){
			stat = 1;
			msg ="您还没有登录，不能发表回复";
			return SUCCESS;
		}
		Review review = reviewService.getReviewById(pid);
		if(review == null ){
			stat = 2;
			msg ="回复的评论不存在！！！";
			return SUCCESS;
		}
		Reply reply = new Reply();
		reply.setAuthorName(author.getNickname());
		reply.setUser(author);
		reply.setContent(content);
		reply.setDate(Utils.formatDate());
		reply.setReview(review);
		reply.setReviewUsername(review.getAuthorName());
		replyService.save(reply);
		stat = 0;
		msg = "评论成功！！！";
		return SUCCESS;
	}
	public String me() throws Exception {
		User author = (User) ActionContext.getContext().getSession().get(LoginAction.SESSION_USER);
		if(author == null ){
			stat = 1;
			msg ="您还没有登录，不能发表回复";
			return SUCCESS;
		}
		Review review = reviewService.getReviewById(pid);
		if(review == null ){
			stat = 2;
			msg ="回复的评论不存在！！！";
			return SUCCESS;
		}
		Reply me = replyService.getReplyById(rid);
		if(me == null ){
			stat = 2;
			msg ="回复的回复不存在！！！";
			return SUCCESS;
		}
		Reply reply = new Reply();
		reply.setAuthorName(author.getNickname());
		reply.setUser(author);
		reply.setContent(content);
		reply.setDate(Utils.formatDate());
		reply.setReview(review);
		reply.setReviewUsername(me.getAuthorName());
		replyService.save(reply);
		stat = 0;
		msg = "回复成功！！！";
		return SUCCESS;
	}

	public void setContent(String content) {
		this.content = content;
	}
	public void setPid(int pid) {
		this.pid = pid;
	}
	public void setRid(int rid) {
		this.rid = rid;
	}
	public String getMsg() {
		return msg;
	}
	public int getStat() {
		return stat;
	}
}
